<template>
  <div class="app-container">
    <div class="filter-box">
      <el-button type="primary" size="small" @click="handleAdd">新增用户</el-button>
    </div>
    <!-- 数据列表 -->
    <el-table :data="tableData" border style="width: 100%;">
      <el-table-column prop="account" label="用户账号" align="center" />
      <el-table-column prop="name" label="用户昵称" align="center" />
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-tag
            size="medium"
            :type="scope.row.status === 1 ? 'success' : 'danger'"
          >{{ scope.row.status === 1 ? '启用' : '禁用' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建日期" align="center" />
      <el-table-column prop="updated_at" label="修改时间" align="center" />
      <el-table-column label="角色" align="center">
        <template slot-scope="scope">
          <el-popover
            v-for="item in scope.row.roles"
            :key="item.id"
            trigger="hover"
            placement="top"
          >
            <p>{{ item.description }}</p>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">{{ item.name }}</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.pageSize"
      @pagination="getTableData"
    />

    <!-- 新增/编辑 弹窗 -->
    <el-dialog
      :title="type"
      :visible.sync="dialogFormVisible"
      :destroy-on-close="true"
      @closed="handleClose"
    >
      <el-form ref="userForm" :model="userForm">
        <el-form-item label="账号" label-width="120px">
          <el-input v-model="userForm.account" autocomplete="off" />
        </el-form-item>
        <el-form-item label="昵称" label-width="120px">
          <el-input v-model="userForm.name" autocomplete="off" />
        </el-form-item>
        <el-form-item v-if="type === '新增用户'" label="密码" label-width="120px">
          <el-input v-model="userForm.password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="角色" label-width="120px">
          <el-select v-model="userForm.roleId" multiple placeholder="请选择">
            <el-option
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" label-width="120px">
          <el-switch
            v-model="userForm.status"
            :active-value="1"
            :inactive-value="2"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { addUser, delUser, listUser, updateUser } from '@/api/system/user'
import { listRole } from '@/api/system/role'
import Pagination from '@/components/Pagination'
export default {
  components: { Pagination },
  data() {
    return {
      tableData: [],
      dialogFormVisible: false,
      type: '',
      userForm: {
        id: '',
        account: '',
        name: '',
        password: '',
        status: 1,
        roleId: []
      },
      roleOptions: [],
      total: 0,
      listQuery: {
        page: 1,
        pageSize: 20
      }
    }
  },
  created() {
    this.getTableData()
  },
  methods: {
    // 获取用户列表
    getTableData() {
      listUser(this.listQuery).then(res => {
        this.tableData = res.data.list
        this.total = res.data.total
      })
    },
    // 新增用户
    async handleAdd() {
      await this.getRoleList()
      this.type = '新增用户'
      this.dialogFormVisible = true
    },
    // 编辑用户
    async handleEdit(index, row) {
      await this.getRoleList()
      this.type = '修改用户'
      const roleId = []
      row.roles.forEach(element => {
        roleId.push(element.id)
      })
      this.userForm = {
        roleId,
        name: row.name,
        account: row.account,
        id: row.id,
        status: row.status,
        password: row.password
      }
      this.dialogFormVisible = true
    },
    // 关闭弹窗 初始化表单数据
    handleClose() {
      this.userForm = {
        id: '',
        account: '',
        name: '',
        status: 1,
        roles: []
      }
      this.$refs.userForm.resetFields()
    },
    // 删除用户
    handleDelete(index, row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delUser(row.id).then(res => {
          this.getTableData()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }).catch(e => {
          this.$message({
            type: 'error',
            message: '删除失败!'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 确认新增 || 修改
    handleConfirm() {
      const { id, account, name, password, roleId, status } = this.userForm
      if (this.type === '新增用户') {
        addUser({ account, name, password, roleId, status }).then(res => {
          this.$message({
            type: 'success',
            message: '新增成功!'
          })
          this.getTableData()
          this.dialogFormVisible = false
        }).catch(e => {
          this.$message({
            type: 'error',
            message: '新增失败!'
          })
          this.dialogFormVisible = false
        })
      } else {
        updateUser(id, { account, name, roleId, password, status }).then(res => {
          this.$message({
            type: 'success',
            message: '修改成功!'
          })
          this.getTableData()
          this.dialogFormVisible = false
        }).catch(e => {
          this.$message({
            type: 'error',
            message: '新增失败!'
          })
          this.dialogFormVisible = false
        })
      }
    },
    // 获取角色列表
    getRoleList() {
      return new Promise((resolve, reject) => {
        if (this.roleOptions.length === 0) {
          listRole().then(res => {
            res.data.list.forEach(element => {
              this.roleOptions.push({
                label: element.name,
                value: element.id
              })
            })
            resolve('ok')
          }).catch(e => {
            reject(e)
          })
        } else {
          resolve('ok')
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.app-container {
  padding: 20px;
  .filter-box {
    margin-bottom: 20px;
    .filter-item {
      font-size: 14px;
      span {
        margin-right: 10px;
      }
    }
  }
}
</style>
